package com.yungam.imcs.controller.process_threshold;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yungam.common.bean.alarm_config.AlarmConfig;
import com.yungam.common.bean.alarm_config.Type;
import com.yungam.common.bean.equip.EquipmentConfig;
import com.yungam.common.bean.process_threshold.ProcessThresholdEntity;
import com.yungam.common.response.RetDTO;
import com.yungam.common.service.AlarmConfigService;
import com.yungam.common.service.EquipmentConfigService;
import com.yungam.other.service.IotService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Api(tags = "工艺阈值管理接口")
@RestController
@RequestMapping("/processThreshold")
public class ProcessThresholdController {

    @Resource
    private EquipmentConfigService equipmentConfigService;
    @Resource
    private AlarmConfigService alarmConfigService;
    @Resource
    private IotService iotService;

    @ApiOperation("阈值下发")
    @PostMapping("/sendParams")
    public RetDTO<?> sendParams(@RequestBody List<ProcessThresholdEntity> reqData,
                                @RequestParam(value = "equId") Integer equId) {
        alarmConfigService.remove(new QueryWrapper<AlarmConfig>()
                .eq("equip_id", equId));
        List<AlarmConfig> list = Lists.newArrayList();
        for (ProcessThresholdEntity entity : reqData) {
            if (isNullValue(entity)) continue;
            if (entity.getType() == 0) { // 数值型
                List<AlarmConfig> acs = Lists.newArrayList(new AlarmConfig(), new AlarmConfig());
                for (AlarmConfig ac : acs) {
                    ac.setId(null)
                            .setEquipId(equId)
                            .setItemId(entity.getParamId())
                            .setGroup(Type.AlarmGroup.Number)
                            .setLevel(entity.getLevel());
                }
                for (int i = 0, n = acs.size(); i < n; i++) {
                    if (i == 0) {
                        acs.get(i).setType(Type.AlarmType.Max).setValue(entity.getMax());
                    } else {
                        acs.get(i).setType(Type.AlarmType.Min).setValue(entity.getMin());
                    }
                }
                list.addAll(acs);
            } else { // 状态型
                AlarmConfig ac = new AlarmConfig();
                ac.setId(null)
                        .setEquipId(equId)
                        .setItemId(entity.getParamId())
                        .setType(Type.AlarmType.EQ)
                        .setGroup(Type.AlarmGroup.Status)
                        .setValue(entity.getAlarmNum())
                        .setLevel(entity.getLevel());
                list.add(ac);
            }
        }
        alarmConfigService.saveBatch(list);
        iotService.updateProcessThreshold(equId, list);
        return RetDTO.success();
    }

    /**
     * 判断工艺参数是否设置了阈值, 没有设置阈值不保存
     * @param entity
     * @return
     */
    private boolean isNullValue(ProcessThresholdEntity entity) {
        boolean flag;
        if (entity.getType() == 0) {
            flag = entity.getMax() == null || entity.getMin() == null;
        } else {
            flag = entity.getAlarmNum() == null;
        }
        return flag;
    }

    /**
     * 查询某一工艺参数的阈值信息
     */
    @ApiOperation("查询某一设备的所有工艺参数的阈值信息")
    @GetMapping("/getOneParam")
    public RetDTO<?> getOneParam(@RequestParam(value = "equId", required = true) Integer equId) {
        List<AlarmConfig> alarmConfigList = alarmConfigService.list(new QueryWrapper<AlarmConfig>()
                .eq("equip_id", equId));
        List<EquipmentConfig> items = equipmentConfigService.list(new QueryWrapper<EquipmentConfig>()
                .eq("equ_id", equId));
        Map<Integer, EquipmentConfig> map = Maps.newHashMap();
        for (EquipmentConfig item : items) map.put(item.getItemId(), item);

        Map<String, List<AlarmConfig>> configMap = Maps.newHashMap();
        for (AlarmConfig ac : alarmConfigList) {
            String key = ac.getEquipId() + "-" + ac.getItemId();
            List<AlarmConfig> od = configMap.getOrDefault(key, Lists.newArrayList());
            od.add(ac);
            configMap.put(key, od);
        }

        List<ProcessThresholdEntity> ans = Lists.newArrayList();
        for (Integer paramId : map.keySet()) {
            ProcessThresholdEntity entity = new ProcessThresholdEntity();
            entity.setParamId(paramId)
                    .setEquId(equId)
                    .setItem(map.get(paramId));
            String key = equId + "-" + paramId;
            List<AlarmConfig> list = configMap.get(key);
            if (list == null) {
                entity.setType(Objects.equals(map.get(paramId).getDataType(), "Status") ? 1 : 0);
                ans.add(entity);
                continue;
            }

            for (AlarmConfig ac : list) {
                if (Objects.equals(ac.getType(), Type.AlarmType.EQ)) {
                    entity.setType(1).setAlarmNum(ac.getValue()).setLevel(ac.getLevel());
                } else if (Objects.equals(ac.getType(), Type.AlarmType.Max)) {
                    entity.setType(0).setMax(ac.getValue()).setLevel(ac.getLevel());
                } else {
                    entity.setType(0).setMin(ac.getValue()).setLevel(ac.getLevel());
                }
            }
            ans.add(entity);
        }
        return RetDTO.data(ans);
    }

}
